<?php
/**
 * Created by PhpStorm.
 * User: Hong
 * Date: 2018/3/24
 * Time: 16:06
 * Function:
 */

namespace Admin\Controllers\Administrator;

use Admin\Controllers\BaseAdminController;
use Admin\Policies\AdminPolicy;
use Admin\Resources\AdminResources;
use Illuminate\Http\Request;
use Platform\Models\Admin\Administrator;
use Platform\Models\Admin\Permission;
use Platform\Models\Admin\Department;
use Platform\Models\Organize\Leader;
use Platform\Repository\Admin\AdminRepository;
use Platform\System\Tools\ResultTool;


/**
 * @module 员工管理
 * Class UserController
 * @package App\Http\Controllers\Admin\System
 */
class UserController extends BaseAdminController
{
    protected $repository;
    protected $policy;

    /**
     * UserController constructor.
     * @param AdminRepository $repository
     * @param AdminPolicy $policy
     */
    public function __construct(AdminRepository $repository, AdminPolicy $policy)
    {
        parent::__construct();
        $this->repository = $repository;
        $this->policy = $policy;
    }

    /**
     * @permission 员工列表
     * @param Request $request
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function index(Request $request){

        $users = $this->repository->screen($request);
        $user = $this->admin;
        $users = $users->where('role_id',$user->role_id);
        return myResult()->setData($users,AdminResources::class)->setPage($users)->send();

    }

    /**
     * @permission 添加员工
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $data = $this->verify($request);
        $user = Administrator::create($data);

        /* fixme 角色关系改为一对多
        if ($user && is_array($request->get('roles'))) {
            $roleIds = array_filter($request->get('roles'));
            $user->roles()->sync($roleIds);
            $user->savePermissions();
        }
        */

        return myResult()->setCode(ResultTool::CODE_SUCCESS,'新增成功')->send();
    }

    /**
     * @permission 查看员工信息
     * @param Administrator $admin_user
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(Administrator $admin_user)
    {
        $admin_user->load('department');
        return myResult()->setData($admin_user,AdminResources::class)->send();
    }


    /**
     * @permission 查看自身权限信息
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showSelfPermissions()
    {
        $permissions = Permission::get(['id','name','module','uri','method']);
        $my_permissions = $this->admin->allPermissions();

        $data = Permission::makeData($permissions,$my_permissions);
        return myResult()->setData($data)->send();
    }

    /**
     * @permission 修改员工信息
     * @param Administrator $admin_user
     * @param Request $request
     * @return ResultTool
     */
    public function update(Administrator $admin_user, Request $request)
    {
        $this->policy->update($this->admin,$admin_user);

        $data = $this->verify($request,$admin_user);

        $admin_user->update($data);

        /* fixme 角色关系改为一对多
        $roleIds = array_filter($request->get('roles'));
        if (!empty($roleIds)) {
            $admin_user->roles()->sync($roleIds);
            $admin_user->savePermissions();
        }
        */

        return myResult()->setCode(ResultTool::CODE_SUCCESS,'编辑成功')->send();
    }

    /**
     * @permission 删除员工
     * @param Administrator $admin_user
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(Administrator $admin_user)
    {
        $this->policy->destroy($this->admin,$admin_user);
        $admin_user->delete();
        return myResult()->setCode(ResultTool::CODE_SUCCESS,'删除成功')->send();
    }

    /**
     * 获取上传的头像
     * @param Request $request
     * @return false|null|string
     * 上传图片方式改变，暂停使用
    protected function getAvatar(Request $request)
    {
        if ($request->hasFile('avatar')) {
            $avatar = $request->file('avatar')->store('avatar', 'public');
            pressImg(Storage::disk('public')->path($avatar),100,100);
            return $avatar;
        }
        return null;
    }
    */

    /**
     * 数据验证
     * @param Request $request
     * @param Administrator $admin
     * @return array
     */
    public function verify(Request $request,Administrator $admin = null){

        $data = $request->only(['username','password','name','avatar','department']);

        if ($admin){
            if (isset($data['username'])) unset($data['username']);

            if (!isset($data['password']) || empty($data['password'])) {
                unset($data['password']);
            }else{
                $data['password'] = bcrypt($data['password']);
            }

            if ($admin->isAdmin()){
                unset($data['department']); //fixme 默认用户不可更改角色
            }

        }else {

            if (empty($data['username']))
                myResult()->stop(ResultTool::CODE_PARAM_LOST,'用户名不可为空');

            if (getStrLength($data['username']) > 20)
                myResult()->stop(ResultTool::CODE_PARAM_WRONG,'用户名过长');

            $admin_log = $this->repository->getOneByUsername($data['username']);
            if ($admin_log)
                myResult()->stop(ResultTool::CODE_TARGET_WRONG,'用户名已被使用');

            if (empty($data['password']))
                myResult()->stop(ResultTool::CODE_PARAM_LOST,'密码不可为空');

            $data['password'] = bcrypt($data['password']);
        }


        if (empty($data['name']))
            myResult()->stop(ResultTool::CODE_PARAM_LOST,'昵称不可为空');

        if (getStrLength($data['name']) > 20)
            myResult()->stop(ResultTool::CODE_PARAM_WRONG,'昵称过长');

        $data['department_id'] = null;
        if (isset($data['department'])){
            $role_log = Department::find($data['department']);
            if ($role_log) {
                $data['department_id'] = $data['department'];
            }
            unset($data['role']);
        }


        return $data;
    }
}